// 登录页面
import { useState, useEffect, useRef } from "react";
import { useNavigate } from "react-router-dom";
// react-router-dom components
import { Link } from "react-router-dom";

// @mui material components
import Card from "@mui/material/Card";
import Switch from "@mui/material/Switch";

// Soft UI Dashboard PRO React components
import SoftBox from "components/SoftBox";
import SoftTypography from "components/SoftTypography";
import SoftInput from "components/SoftInput";
import SoftButton from "components/SoftButton";
import SoftAvatar from "components/SoftAvatar";

// Authentication layout components
import LoginLayout from "./components/LoginLayout";
import Socials from "layouts/authentication/components/Socials";
import Separator from "layouts/authentication/components/Separator";

// Images
import curved9 from "assets/images/curved-images/loginBg.png";
import logo from "assets/icon/metamaskLogo.png";
import { emailLogin, sendEmail, getNonce, walletLogin } from "request/api";
import SoftSnackbar from "components/SoftSnackbar";

// formik components
import { Formik, Form } from "formik";
import FormField from "layouts/pages/users/new-user/components/FormField";
import { message } from "antd";
import SelectPlanModal from "pages/BuyPlan/SelectPlan";
// store
import { setToken, fetchUserInfo } from "store/modules/app";
import { useDispatch } from "react-redux";
import { connectMetaMask,signMessage } from "utils/web3";
function Login() {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const selectPlanModalRef = useRef();
  const [errorTooltip, setErrorTooltip] = useState(false);
  useEffect(() => {
    emailLoginHandle();
  }, []);
  const openModal = () => {
    selectPlanModalRef.current.openModal();
  };
  const emailLoginHandle = async () => {};
  let [rememberMe, setRememberMe] = useState(false);

  let handleSetRememberMe = () => setRememberMe(!rememberMe);

  let [sendCodeStatus, setSendCodeStatus] = useState(true);
  let [sendCodeText, setSendCodeText] = useState("Send");
  let [countdown, setCountdown] = useState(10);
  // 发送验证码
  const sendCodeEmail = async (email) => {
    let settime = setInterval(() => {
      if (countdown == 0) {
        //发送验证码
        setSendCodeText("Resend");
        setCountdown(59);
        setSendCodeStatus(true);
        clearInterval(settime);
        return false;
      } else {
        setSendCodeStatus(false);
        setSendCodeText(countdown + "s");
        setCountdown(countdown--);
      }
    }, 1000);
    let params = {
      email,
      event: "login",
    };
    let res = await sendEmail(params);
    if (res.code == 200) {
      message.success(res.msg);
    } else {
      message.success(res.msg);
      // message.error("Send failed");
    }
  };
  //点击登录按钮
  const handleSubmit = async (values, { setSubmitting }) => {
    let params = {
      email: values.email,
      code: values.code,
    };
    let res = await emailLogin(params);
    console.log(res);
    if (res.code == 400) {
      return setErrorTooltip(true);
    } else if (res.code == 0) {
      return message.error(res.msg);
    }
    setSubmitting(false);
    await dispatch(setToken(res.data.token));
    await dispatch(fetchUserInfo());
    navigate("/projects");
  };
  // 错误提示
  const renderError = (
    <SoftSnackbar
      color="error"
      icon="warning"
      title="You are not a subscriber"
      content="You are not a subscriber to Tradingsignal.ai. Please sign up for our Free/Premium to log in to Tradingsignal.ai."
      open={errorTooltip}
      onClose={() => setErrorTooltip(false)}
      close={() => setErrorTooltip(false)}
      bgWhite
    />
  );
  // 小狐狸登录
  const loginMetamask = async () => {
    try {
      const { signer, address } = await connectMetaMask();
      const signNonce = await getNonce({ address });
      const signature = await signMessage(signer, signNonce.nonce);
      const result = await walletLogin({ address, signature });
      if (result.code == 200) {
        await dispatch(setToken(result.data.token));
        await dispatch(fetchUserInfo());
        navigate("/projects");
      }
    } catch (error) {
      console.error("用户拒绝连接或发生错误:", error);
      // ElMessage({
      //   type: "error",
      //   message: error.message,
      // });
    }
  };

  return (
    <LoginLayout title="Welcome Back!" image={curved9}>
      <Card>
        <SoftBox p={3} mb={1} textAlign="center">
          <SoftTypography variant="h5" fontWeight="medium">
            Sign in
          </SoftTypography>
        </SoftBox>
        <SoftBox mb="36px">
          <SoftBox display="flex" justifyContent="center" height="58px" onClick={loginMetamask}>
            <SoftButton variant="outlined" color="light">
              <SoftAvatar src={logo} alt="Avatar" size="xs" />
            </SoftButton>
          </SoftBox>
        </SoftBox>
        <SoftBox px={3} position="relative">
          {/* <SoftBox component="form" role="form"> */}
          {/* <SoftBox mb={2}>
              <SoftInput type="email" placeholder="Email" />
            </SoftBox> */}
          <Formik
            initialValues={{ email: "", code: "" }}
            validate={(values) => {
              const errors = {};
              if (!values.email) {
                errors.email = "Required";
              } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(values.email)) {
                errors.email = "Invalid email address";
              }
              return errors;
            }}
            onSubmit={handleSubmit}
          >
            {({ values, errors, touched, isSubmitting }) => (
              <Form autoComplete="off">
                {/* {console.log(123, values, errors, touched, isSubmitting)} */}
                <SoftBox>
                  <FormField
                    type="email"
                    label=""
                    name="email"
                    value={values.email}
                    placeholder="Enter your email"
                    error={errors.email && touched.email}
                  />
                </SoftBox>
                <SoftBox position="relative">
                  {/* <SoftInput
                    type="text"
                    value={values.code}
                    placeholder="Verification code"
                    onKeyUp={(event) => {
                      if (event.target.value.length > 6) {
                        event.target.value = event.target.value.slice(0, 6);
                      }
                    }}
                  /> */}
                  <FormField
                    type="text"
                    label=""
                    name="code"
                    value={values.code}
                    placeholder="Verification code"
                    error={false}
                    onKeyUp={(event) => {
                      if (event.target.value.length > 6) {
                        event.target.value = event.target.value.slice(0, 6);
                      }
                    }}
                  />
                  <SoftButton
                    fontWeight="regular"
                    size="small"
                    variant="text"
                    color="dark"
                    disabled={
                      !sendCodeStatus ||
                      (values.email ? false : true) ||
                      errors.email == "Invalid email address"
                        ? true
                        : false
                    }
                    sx={{
                      p: 0,
                      m: 0,
                      lineHeight: 1,
                      minWidth: "0",
                      cursor: "pointer",
                      position: "absolute",
                      right: "12px",
                      top: "14px",
                      textTransform: "capitalize",
                    }}
                    onClick={() => sendCodeEmail(values.email)}
                  >
                    {sendCodeText}
                  </SoftButton>
                </SoftBox>

                <SoftBox mt={4} mb={1}>
                  <SoftButton
                    type="submit"
                    disabled={isSubmitting}
                    variant="gradient"
                    color="info"
                    fullWidth
                  >
                    sign in
                  </SoftButton>
                </SoftBox>
              </Form>
            )}
          </Formik>

          <Separator />
          <SoftBox mt={1} mb={2}>
            <SoftButton variant="gradient" color="dark" fullWidth onClick={openModal}>
              Subscribe
            </SoftButton>
            <SelectPlanModal ref={selectPlanModalRef} />
          </SoftBox>
          <SoftBox lineHeight={1} textAlign="center" mb={3}>
            <SoftTypography
              variant="button"
              fontWeight="regular"
              fontSize="12px"
              sx={{ color: "#8392AB" }}
            >
              If you are not a subscriber to Tradingsignal.ai. Please sign up for our Free/Premium
              to log in to Tradingsignal.ai.
            </SoftTypography>
          </SoftBox>
        </SoftBox>
        {renderError}
      </Card>
    </LoginLayout>
  );
}

export default Login;
